<script lang="ts" setup>
import navBar from '@/components/navBar/navBar.vue'
import { computed, onActivated, onDeactivated, onMounted, reactive, ref } from 'vue';
import { pageScrollTop,getScrollTop } from '@/util/bussinessTool'
let curNav = ref(0)
let navHeight = ref(0)
let tabHeight = ref(46)
const scrollTop = reactive(new pageScrollTop(()=>{
    scrollTop.scrollTop = getScrollTop()
}))
type item = {
    name: string,
    id: string
}
const props = defineProps({
    bgColor: {
        type: String,
        default: '#ffffff'
    },
    navList: {
        type: Array<item>,
        default: () => [{ name: '项目介绍', id: 'detail' }, { name: '下单须知', id: 'notice' }]
    }
})

onActivated(() => {
    let bar = document.getElementsByClassName('navbarScroll')
    navHeight.value = (bar[0] as HTMLElement).offsetHeight
    scrollTop.setListener()
})

onDeactivated(() => {
    scrollTop.removeListener()
})

const showNav = computed(() => {
    return scrollTop.scrollTop > navHeight.value ? true : false
})

function onTab(index: number) {
    curNav.value = index
    let pageEle = document.getElementById(props.navList[index].id)
    let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
    if(!pageEle) return
    let rect = pageEle.getBoundingClientRect()
    let top = scrollTop + rect.top - navHeight.value - tabHeight.value
    if (index === 0) {
        window.scrollTo({
            top:top,
            behavior:'smooth',
        })
    } else if (index === 1) {
        window.scrollTo({
            top: top,
            behavior:'smooth',
        })
    }
}

const barStyle = computed(() => {
    return {
        top: navHeight.value + 'px',
        backgroundColor: props.bgColor,
        height: tabHeight.value + 'px'
    }
})

</script>
<template>
    <navBar class="navbarScroll" />
    <div :style="{ height: barStyle.height }" v-if="showNav">
        <div class="i-text-15 i-py-5 flex items-center justify-around fixed z-10 w-full" :style="barStyle">
            <div class="i-py-10 " v-for="(item, index) in props.navList" :key="index" @click="onTab(index)"
                :class="curNav === index ? 'text-green-600' : 'text-gray-300'">
                {{ item.name }}
            </div>
        </div>
    </div>
</template>
<style >

</style>
